extends CharacterBody2D
class_name GoldEnemy

@export var stats: PandoraEntity
@onready var enemy_health_component: EnemyHealthComponent = %EnemyHealthComponent
@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D

# 金币怪配置
@export var max_hits: int = 200  # 总共能被打的次数
@export var gold_per_hit: int = 10  # 每次攻击获得的金币
@export var bonus_gold: int = 1000  # 打完后的额外奖励
@export var move_speed: float = 150.0  # 移动速度

# 路径点
@export var start_point: Node2D
@export var end_point: Node2D

# 内部状态
var current_hits: int = 0
var gold_stats: PandoraEntity
## 被打第一下后开始移动
var is_start = false

signal gold_earned(amount: int)
signal gold_defeated()

func _ready() -> void:
	gold_stats = stats.instantiate()
	enemy_health_component.hurt.connect(_on_hurt)
	
func _physics_process(delta: float) -> void:
	if !is_start:
		return
	# 简单的路径移动
	_move_along_path(delta)

func _move_along_path(_delta: float) -> void:
	var target_point = end_point
	var direction = global_position.direction_to(target_point.global_position)
	
	velocity = direction * move_speed
	move_and_slide()

	# 检查是否到达目标点
	if global_position.distance_to(target_point.global_position) < 5.0:
		set_physics_process(false)
		_die()

func _on_hurt() -> void:
	is_start = true
	# 每次攻击算作一次打击
	current_hits += 1
	# 给予玩家金币奖励
	Utils.set_player_stats_value("gold", gold_per_hit)
	gold_earned.emit(gold_per_hit)
	
	# 显示金币获得效果
	_show_gold_effect(gold_per_hit)
	
	# 检查是否达到最大打击次数
	if current_hits >= max_hits:
		_die(true)

func _show_gold_effect(amount: int) -> void:
	Utils.show_string_label_c("金币+%s" % amount, Utils.player, Color.YELLOW)

	# 播放受伤动画
	if sprite:
		sprite.modulate = Color.WHITE
		var tween = create_tween()
		tween.tween_property(sprite, "modulate", Color.RED, 0.1)
		tween.tween_property(sprite, "modulate", Color.WHITE, 0.1)

func _die(have_reward: bool = false) -> void:

	# 给予额外奖励
	if have_reward:
		Utils.set_player_stats_value("gold", bonus_gold)
		gold_earned.emit(bonus_gold)
		# 显示额外奖励效果
		_show_gold_effect(bonus_gold)
	
	
	# 播放死亡动画
	if sprite:
		var tween = create_tween()
		tween.tween_property(sprite, "modulate:a", 0.0, 0.5)
		tween.tween_callback(queue_free)
	
	# 通知系统金币怪已被击败
	gold_defeated.emit()
	
	await get_tree().create_timer(0.5).timeout
	EventBus.push_event("to_des", ["main_scene"])
	queue_free()

# 获取剩余打击次数
func get_remaining_hits() -> int:
	return max_hits - current_hits
	
func get_stats():
	return gold_stats

func set_start_point(_start_point):
	start_point = _start_point
	# 初始化位置
	global_position = start_point.global_position
	
func set_end_point(_end_point):
	end_point = _end_point
